package leetcode.L31;

class Solution {
    public void nextPermutation(int[] nums) {
        //1. 找到一个a[i]<a[i+1]
        //2. 找到一个a[j]>a[i]并交换
        //3. a[i+1]后面的交换
        int i = nums.length - 2;
        while (i >= 0 && nums[i] >= nums[i + 1]) {
            i--;
        }
        if (i >= 0) {
            int j = nums.length - 1;
            while (j >= 0 && nums[i] >= nums[j]) {
                j--;
            }
            swap(i, j, nums);
        }
        reverse(i + 1, nums);
    }

    private void swap(int i, int j, int[] nums) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }

    private void reverse(int start, int[] nums) {
        int left = start;
        int right = nums.length-1;
        while (left < right) {
            swap(left, right, nums);
            left++;
            right--;
        }
    }
}